<template>
  <div class="p-2">
    <el-row :gutter="20">
      <!-- 服务分类 -->
      <el-col :lg="4" :xs="24" style="">
        <el-card shadow="hover">
          <el-input v-model="categoryName" placeholder="请输入分类名称" prefix-icon="Search" clearable />
          <el-tree
            ref="categoryTreeRef"
            class="mt-2"
            node-key="id"
            :data="categoryOptions"
            :props="{ label: 'label', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            highlight-current
            @node-click="handleNodeClick"
          />
        </el-card>
      </el-col>
      <el-col :lg="20" :xs="24">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div v-show="showSearch" class="mb-[10px]">
            <el-card shadow="hover">
              <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <el-form-item label="服务名称" prop="spuName">
                  <el-input v-model="queryParams.spuName" placeholder="请输入服务名称" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </transition>
        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['spu:spu:add']">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['spu:spu:edit']">修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['spu:spu:remove']">删除</el-button>
              </el-col>
<!--              <el-col :span="1.5">-->
<!--                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleOrder()" v-hasPermi="['lawyer:spu:edit']">生成订单(测试)</el-button>-->
<!--              </el-col>-->
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>
          <el-table v-loading="loading" :data="spuList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="主键ID" align="center" prop="spuId" v-if="false" />
            <el-table-column label="服务类别" align="center" prop="categoryName" />
            <el-table-column label="服务名称" align="center" prop="spuName" />
            <el-table-column label="封面图片" align="center" prop="mainImgUrl">
              <template #default="scope">
                <el-image :src="scope.row.mainImgUrl" :preview-src-list="[scope.row.mainImgUrl]" :preview-teleported="true"
                          :lazy="true" fit="cover" style="width: 59px; height:59px; "/>
              </template>
            </el-table-column>
            <el-table-column label="售价(元)" align="center" prop="priceFee">
              <template #default="scope">
                <el-text>{{ scope.row.priceFee / 100 }} 元</el-text>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="spuStatus">
              <template #default="scope">
                <el-text type="danger" v-if="scope.row.spuStatus === '0'">已下架</el-text>
                <el-text type="success" v-else>已发布</el-text>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['spu:spu:edit']"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['spu:spu:remove']"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>

        <!-- 添加或修改商品信息对话框 -->
        <el-dialog :title="dialog.title" v-model="dialog.visible" width="839px" append-to-body>
          <el-form ref="spuFormRef" :model="form" :rules="rules" label-width="110px">
            <el-form-item label="服务封面图" prop="mainImgUrl">
              <imageUpload single :limit="1" v-model="form.mainImgUrl" />
            </el-form-item>
            <el-form-item label="服务名称" prop="spuName">
              <el-input v-model="form.spuName" placeholder="请输入服务名称" />
            </el-form-item>
            <el-form-item label="服务分类" prop="categoryId">
              <el-tree-select
                v-model="form.categoryId"
                :data="categoryOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="id"
                placeholder="请选择服务分类"
                check-strictly
              />
            </el-form-item>
            <el-form-item label="售价(元)" prop="priceFeeYuan">
              <el-input-number v-model="form.priceFeeYuan" :min="0" :precision="2" :step="0.1" controls-position="right"/>
            </el-form-item>
            <el-form-item label="市场价(元)" prop="marketPriceFeeYuan">
              <el-input-number v-model="form.marketPriceFeeYuan" :min="0" :precision="2" :step="0.1" controls-position="right"/>
            </el-form-item>
            <el-form-item label="状态" prop="spuStatus">
              <el-radio-group v-model="form.spuStatus">
                <el-radio :value="'1'">发布</el-radio>
                <el-radio :value="'0'">下架</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="简介" prop="spuDesc">
              <el-input v-model="form.spuDesc" type="textarea" :rows="6" placeholder="请输入服务简介" />
            </el-form-item>
            <el-form-item label="详情" prop="spuDetail">
              <editor v-model="form.spuDetail" :min-height="32" />
            </el-form-item>
            <el-form-item label="附件" prop="subtitle">
              <el-text size="default" style="width: 100%">多个文件请打包后上传</el-text>
              <FileUpload v-model="form.subtitle" :file-list="[form.subtitle]" :limit="1" :fileSize="30" :fileType="['doc', 'docx', 'pptx', 'xlsx', 'xls', 'ppt', 'pptx', 'txt', 'pdf','rar','zip']"/>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Spu" lang="ts">
import { SpuVo, SpuForm, SpuQuery } from '@/api/spu/spu/types';
import { listSpu, addSpu, getSpu, delSpu, updateSpu } from '@/api/spu/spu';
import { CategoryVo } from '@/api/spu/category/types';
import { getCategoryTreeSelect } from '@/api/spu/category';
import { createOrder } from '@/api/trade/order';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const spuList = ref<SpuVo[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const categoryName = ref('');
const categoryOptions = ref<CategoryVo[]>([]);
const categoryTreeRef = ref<ElTreeInstance>();
const spuFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: SpuForm = {
  spuId: undefined,
  categoryId: undefined,
  categoryName: undefined,
  categoryParentId: undefined,
  spuName: undefined,
  subtitle: undefined,
  mainImgUrl: undefined,
  secImgUrl: undefined,
  priceFee: 0,
  priceFeeYuan: 0,
  marketPriceFee: 0,
  marketPriceFeeYuan: 0,
  spuStatus: '1',
  saleTrack: undefined,
  spuDesc: undefined,
  spuDetail: undefined
};

const data = reactive<PageData<SpuForm, SpuQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryId: undefined,
    spuName: undefined,
    params: {
    }
  },
  rules: {
    spuId: [
      { required: true, message: "主键ID不能为空", trigger: "blur" }
    ],
    categoryId: [
      { required: true, message: "服务分类不能为空", trigger: "blur" }
    ],
    categoryName: [
      { required: true, message: "服务分类名称不能为空", trigger: "blur" }
    ],
    spuName: [
      { required: true, message: "服务名称不能为空", trigger: "blur" }
    ],
    mainImgUrl: [
      { required: true, message: "服务封面图不能为空", trigger: "blur" }
    ],
    priceFee: [
      { required: true, message: "售价不能为空", trigger: "blur" }
    ],
    marketPriceFee: [
      { required: true, message: "市场价不能为空", trigger: "blur" }
    ],
    spuDesc: [
      { required: true, message: "服务简介不能为空", trigger: "blur" }
    ],
    spuDetail: [
      { required: true, message: "服务详情不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

/** 根据名称筛选分类树 */
watchEffect(
  () => {
    categoryTreeRef.value?.filter(categoryName.value);
  },
  {
    flush: 'post' // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);

/** 查询服务分类下拉树结构 */
const getTreeSelect = async () => {
  const res = await getCategoryTreeSelect();
  categoryOptions.value = res.data;
};

/** 节点单击事件 */
const handleNodeClick = (data: CategoryVo) => {
  queryParams.value.categoryId = data.id;
  console.log(data);
  //queryParams.value.deptId = undefined;
  handleQuery();
};

/** 查询商品列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSpu(queryParams.value);
  spuList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  spuFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  // if (queryParams.value.categoryId) {
  //  // queryParams.value.belongDeptId = undefined;
  // }
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  queryParams.value.categoryId = undefined;
  categoryTreeRef.value?.setCurrentKey(undefined);
  /** 清空左边部门树选中值 */
  //queryParams.value.categoryId = undefined;
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: SpuVo[]) => {
  ids.value = selection.map(item => item.spuId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加服务信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: SpuVo) => {
  reset();
  const _spuId = row?.spuId || ids.value[0];
  const res = await getSpu(_spuId);
  Object.assign(form.value, res.data);
  form.value.priceFeeYuan = form.value.priceFee / 100;
  form.value.marketPriceFeeYuan = form.value.marketPriceFee / 100;
  dialog.visible = true;
  dialog.title = '修改服务信息';
};

/** 提交按钮 */
const submitForm = () => {
  spuFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.priceFee = form.value.priceFeeYuan * 100;
      form.value.marketPriceFee = form.value.marketPriceFeeYuan * 100;
      if (form.value.spuId) {
        await updateSpu(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addSpu(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: SpuVo) => {
  const _spuIds = row?.spuId || ids.value;
  await proxy?.$modal.confirm('是否确认删除当前选中的数据项？').finally(() => loading.value = false);
  await delSpu(_spuIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};
const handleOrder = async (row?: SpuVo) => {
  const _spuId = row?.spuId || ids.value[0];
  await createOrder(_spuId);
  proxy?.$modal.msgSuccess('删除成功');
};

onMounted(() => {
  getTreeSelect(); // 初始化分类数据
  getList();
});
</script>
